<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>canvas电子签名</title>
	<meta charset="utf-8">
	<style type="text/css">
		#myCanvas {
			border: 1px solid rgb(153, 151, 151);
		}

		button {
			padding: 10px 20px;
			border: none;
		}
	</style>
</head>

<body>
	<canvas id='myCanvas' width="350" height="500"></canvas>
	<div id="image"></div>
	<button id="save">完成</button>
	<button id="clearCanvas">重置</button>
	<div id="img"></div>
	<p>
		主要通过获取移动轨迹坐标，content.beginPath绘制线条 实现描绘功能
	</p>
</body>
<script type="text/javascript">

	let Ocanvas = document.getElementById('myCanvas') //Ocanvas画布
	let content = Ocanvas.getContext('2d')
	let Oimg = document.getElementById('img')
	Ocanvas.ontouchstart = function (e) { //触摸事件开始
		let x = e.changedTouches[0].clientX - Ocanvas.offsetLeft
		let y = e.changedTouches[0].clientY - Ocanvas.offsetTop

		content.beginPath()
		content.strokeStyle = '#000000'
		content.lineWidth = 3
		content.moveTo(x, y) //开始位置
		Ocanvas.ontouchmove = function (e) { //触摸事件移动
			var x = e.changedTouches[0].clientX - Ocanvas.offsetLeft
			var y = e.changedTouches[0].clientY - Ocanvas.offsetTop
			content.lineTo(x, y) //最终位置
			content.stroke()
		}
	}

	//清除画布
	let clearBtn = document.getElementById('clearCanvas')
	clearBtn.onclick = function () {
		content.clearRect(0, 0, Ocanvas.width, Ocanvas.height)
		Oimg.querySelector('img').remove()
	}

	//生成图片
	let saveImg = document.getElementById('save')
	saveImg.onclick = function () {
		let img = new Image()
		img.src = Ocanvas.toDataURL("image/png") //得到base64 图片
		Oimg.appendChild(img)
	}
</script>

</html>